"use client";

// 下拉组件

import { DropdownMenuContentProps } from "@radix-ui/react-dropdown-menu";
import {
  DropdownMenu,
  DropdownMenuTrigger,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
} from "@/components/ui/dropdown-menu";
import { Link2, Trash2, Pencil } from "lucide-react"; // icon 图标
import { toast } from "sonner";
import { useApiMutation } from "@/hooks/use-api-mutaion";
import { api } from "@/convex/_generated/api";
import { ConfirmModal } from "@/components/confirm-modal";
import { Button } from "./ui/button";
import { useRenamenModal } from "@/store/use-rename-modal";

interface ActionsProps {
  children: React.ReactNode;
  side?: DropdownMenuContentProps["side"];
  sideOffset?: DropdownMenuContentProps["sideOffset"];
  id: string;
  title: string;
}

export const Actions = ({
  children,
  side,
  sideOffset,
  id,
  title,
}: ActionsProps) => {
  const { mutate, pending } = useApiMutation(api.board.remove);
  const { onOpen } = useRenamenModal();

  const onCopyClick = () => {
    // 将文本内容写入剪贴板
    navigator.clipboard
      // 返回主机协议端口 http://localhost:3000
      .writeText(`${window.location.origin}/board/${id}`)
      .then(() => {
        toast.success("复制成功");
      })
      .catch(() => {
        toast.error("复制失败");
      });
  };

  const onDelete = () => {
    mutate({ id })
      .then(() => toast.success("会员移除成功"))
      .catch(() => toast.error("会员移除失败"));
  };

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>{children}</DropdownMenuTrigger>
      <DropdownMenuContent
        side={side}
        sideOffset={sideOffset}
        className="w-60"
        onClick={(e) => e.stopPropagation()}
      >
        <DropdownMenuItem className="p-3 cursor-pointer" onClick={onCopyClick}>
          <Link2 className="h-4 w-4 mr-2 "></Link2>
          复制会员链接
        </DropdownMenuItem>
        <DropdownMenuItem
          className="p-3 cursor-pointer"
          onClick={() => onOpen(id, title)}
        >
          <Pencil className="h-4 w-4 mr-2 "></Pencil>
          重命名
        </DropdownMenuItem>
        <ConfirmModal
          header="确认是否删除"
          description="删除之后不可恢复，请确认是否删除"
          disabled={pending}
          onConfirm={onDelete}
        >
          <Button
            variant="ghost"
            className="w-full p-3 justify-start text-sm cursor-pointer"
          >
            <Trash2 className="h-4 w-4 mr-2 "></Trash2>
            移除会员
          </Button>
        </ConfirmModal>
      </DropdownMenuContent>
    </DropdownMenu>
  );
};
